import http from '@ohos.net.http';
import { Song, Playlist, Rank } from './DataModel';

/**
 * 酷狗音乐API封装类
 * 基于酷狗公开接口实现，用于获取音乐数据
 */
export class KugouApi {
  private baseUrl: string = 'https://wwwapi.kugou.com';
  private headers = {
    'Content-Type': 'application/json',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
  };

  /**
   * 获取音乐播放地址
   * @param hash 歌曲哈希值
   * @param albumId 专辑ID
   */
  async getPlayUrl(hash: string, albumId: string = ''): Promise<string> {
    const url = `https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash=${hash}&album_id=${albumId}&dfid=25dX2o3U3l0a1E4x0I2C6E6m&mid=3f0c3b3d1a23f9a4a5f5a3d4c3e4e65&platid=4`;
    const result = await this.sendRequest(url);
    return result.data.play_url || '';
  }

  /**
   * 搜索歌曲
   * @param keyword 搜索关键词
   * @param page 页码
   * @param pageSize 每页数量
   */
  async searchSongs(keyword: string, page: number = 1, pageSize: number = 20): Promise<Song[]> {
    const url = `https://complexsearch.kugou.com/v2/search/song?callback=callback123&keyword=${encodeURIComponent(keyword)}&page=${page}&pagesize=${pageSize}&showtype=1`;
    const result = await this.sendRequest(url);
    const songList: Song[] = [];

    if (result.data && result.data.info) {
      result.data.info.forEach((item: any) => {
        songList.push({
          hash: item.FileHash || '',
          name: item.SongName || '',
          singer: item.SingerName || '',
          album: item.AlbumName || '',
          duration: item.Duration || 0,
          albumId: item.AlbumID || '',
          coverUrl: item.AlbumPicBig || ''
        });
      });
    }

    return songList;
  }

  /**
   * 获取热门歌单
   * @param page 页码
   * @param pageSize 每页数量
   */
  async getHotPlaylists(page: number = 1, pageSize: number = 10): Promise<Playlist[]> {
    const url = `https://wwwapi.kugou.com/playlist/index?page=${page}&pagesize=${pageSize}&plat=0&version=9108&tagid=0&withsong=1`;
    const result = await this.sendRequest(url);
    const playlistList: Playlist[] = [];

    if (result.data && result.data.info) {
      result.data.info.forEach((item: any) => {
        const playlist: Playlist = {
          id: item.specialid || '',
          name: item.specialname || '',
          coverUrl: item.imgurl || '',
          songList: []
        };

        if (item.songlist && item.songlist.length > 0) {
          item.songlist.forEach((songItem: any) => {
            playlist.songList.push({
              hash: songItem.hash || '',
              name: songItem.songname || '',
              singer: songItem.singername || '',
              album: songItem.album_name || '',
              duration: songItem.duration || 0,
              albumId: songItem.album_id || '',
              coverUrl: songItem.imgurl || ''
            });
          });
        }

        playlistList.push(playlist);
      });
    }

    return playlistList;
  }

  /**
   * 获取排行榜列表
   */
  async getRankList(): Promise<Rank[]> {
    const url = `https://wwwapi.kugou.com/rank/list&json=true`;
    const result = await this.sendRequest(url);
    const rankList: Rank[] = [];

    if (result.data && result.data.ranklist) {
      result.data.ranklist.forEach((item: any) => {
        rankList.push({
          id: item.rankid.toString() || '',
          name: item.rankname || '',
          coverUrl: item.imgurl || '',
          songList: []
        });
      });
    }

    return rankList;
  }

  /**
   * 获取排行榜详情
   * @param rankId 排行榜ID
   * @param page 页码
   * @param pageSize 每页数量
   */
  async getRankDetail(rankId: string, page: number = 1, pageSize: number = 30): Promise<Rank> {
    const url = `https://wwwapi.kugou.com/rank/info/?rankid=${rankId}&page=${page}&pagesize=${pageSize}&plat=0&version=9108`;
    const result = await this.sendRequest(url);
    const rank: Rank = {
      id: rankId,
      name: result.data.rankname || '',
      coverUrl: result.data.imgurl || '',
      songList: []
    };

    if (result.data && result.data.songs) {
      result.data.songs.forEach((item: any) => {
        rank.songList.push({
          hash: item.hash || '',
          name: item.songname || '',
          singer: item.singername || '',
          album: item.album_name || '',
          duration: item.duration || 0,
          albumId: item.album_id || '',
          coverUrl: item.imgurl || ''
        });
      });
    }

    return rank;
  }

  /**
   * 发送HTTP请求
   * @param url 请求URL
   * @param method 请求方法
   * @param data 请求数据
   */
  private async sendRequest(url: string, method: string = 'GET', data: any = null): Promise<any> {
    return new Promise((resolve, reject) => {
      const httpRequest = http.createHttp();

      httpRequest.request(
        url,
        {
          method: http.RequestMethod[method as keyof typeof http.RequestMethod],
          header: this.headers,
          readTimeout: 60000,
          connectTimeout: 60000,
          extraData: data
        },
        (err, response) => {
          if (!err && response.responseCode === 200) {
            try {
              // 处理JSONP格式的返回
              let result = response.result.toString();
              if (result.startsWith('callback')) {
                result = result.substring(result.indexOf('(') + 1, result.lastIndexOf(')'));
              }
              resolve(JSON.parse(result));
            } catch (parseError) {
              reject(parseError);
            }
          } else {
            reject(err || new Error(`HTTP request failed with code ${response?.responseCode}`));
          }
          httpRequest.destroy();
        }
      );
    });
  }
}